package com.ssh.nio.channel;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.Random;

public class FileChannelTest {

	public static void main(String[] args) throws IOException {
		// fromChanneltoChannel();

//		Random r = new Random();
//		int count = r.nextInt(10);
//		System.out.println(count);
	}

	private static void fromChanneltoChannel() throws FileNotFoundException,
			IOException {
		RandomAccessFile randomFile = new RandomAccessFile("g:\\abc.txt", "r");

		randomFile.seek(5);

		FileChannel channel = randomFile.getChannel();

		System.out.println(channel.position());
		// 创建写缓冲区
		WritableByteChannel writeChannel = Channels.newChannel(System.out);
		// 分配缓冲区
		ByteBuffer buffer = ByteBuffer.allocate(1024 * 16);
		// 读入buffer
		channel.read(buffer);
		// 准备写数据
		buffer.flip();

		while (buffer.hasRemaining()) {
			// 写入writeChannel
			writeChannel.write(buffer);
		}
	}
}
